package com.lepu.app.fun.index.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.app.application.MyApplication;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.lepu.app.fun.bbs.bean.BeanBbs;
import com.lepu.app.fun.index.adapter.IndexKnowAdapter;
import com.lepu.app.fun.my.bean.BeanMyArticle;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

public class IndexKnowActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener,AsyncRequest,Observer{
	
	private static final String REQUEST_DATA = "request_data";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	
	private CustomTopBarNew topbar;
	
	private GridView mGridView;
	private IndexKnowAdapter mDataAdapter;
	private ArrayList<BeanMyArticle> mDataArrayList = null;
	
	private String mRefreshTime = "";
	private int mPosition = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mNeedDefaultUmeng = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_know_activity);

		init();
	}

    @Override
	public void onResume() {
        super.onResume();

        UmengHelper.onResume(this, UmengEvent.page_shouye_shuhoutiantianzhi);
    }

    @Override
	public void onPause() {
        super.onPause();

        UmengHelper.onPause(this, UmengEvent.page_shouye_shuhoutiantianzhi);
    }
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		ObserverManager.getInstance().removeObserver(ObserverConst.NOTIFY_KNOW_UPDATE);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
			}else{
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if(mDataArrayList == null || mDataArrayList.size() == 0)
				{
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
				
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}
	

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("术后天天知");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mDataArrayList = new ArrayList<BeanMyArticle>();
		
		mGridView = (GridView) findViewById(R.id.gridView);
		mGridView.setNumColumns(4); //设置每行列数
		mGridView.setOnItemClickListener(gridViewListener);
		
		mGridView.setSelected(true);
		
		request();
		showFirstLoadDataLayout(true);
		
		ObserverManager.getInstance().addObserver(ObserverConst.NOTIFY_KNOW_UPDATE, this);
	}
	
	OnItemClickListener gridViewListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
			Intent intent = new Intent(IndexKnowActivity.this, IndexKnowDetailActivity.class);
			intent.putExtra("url", mDataArrayList.get(position).LinkURL);
			intent.putExtra("articleId", mDataArrayList.get(position).ArticleID);
			intent.putExtra("viewCount", mDataArrayList.get(position).ViewCount);
			intent.putExtra("favourCount", mDataArrayList.get(position).FavourCount);
			startActivity(intent,true);
			mPosition = position;
		}
	};
	
	
	// 请求数据
	public void request() {

		String url = Setting.getArticleListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("ACIDList", 17);//同心天天知
			//params.put("ArticleTitle", "");
			params.put("RefreshTime", mRefreshTime);
			params.put("SortDirection", "ASC");
			
			int version = AppManager.getVersionCode(this, getPackageName());
			params.put("ClientVersion", String.valueOf(version));
			
			params.put("PageIndex", 1);
			params.put("PageSize", 1000);

		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this,REQUEST_DATA, true, false, true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressLint("NewApi")
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				//第一次请求用这个
				showFirstLoadDataLayout(false);
				
				ArrayList<BeanMyArticle> dataList = (ArrayList<BeanMyArticle>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataArrayList.addAll(dataList);
					
					String surgicalTime = MyApplication.getInstance().getLoginInfo().SurgicalTime;
					
					int Instrument = UtilityBase.parseInt(MyApplication.getInstance().getLoginInfo().Instrument);
					String[] array = getResources().getStringArray(R.array.array_userinfo_operation_type_old);
					if(Instrument >= array.length)
					{
						Instrument = 0;
					}
					
					if(Instrument == 0){
						surgicalTime = "";
					}
					
					int selectIndex = DateUtil.getKnowThisIndex(surgicalTime);
					mDataAdapter = new IndexKnowAdapter(IndexKnowActivity.this,mDataArrayList,selectIndex);
					mGridView.setAdapter(mDataAdapter);
					
					if(selectIndex<mDataArrayList.size() && selectIndex>7){
						mGridView.setSelection(selectIndex-4);  
					}
					
					topbar.setTopbarTitle(DateUtil.getKnowThisDate(surgicalTime));
				} else {
					UIHelper.showToast(IndexKnowActivity.this, R.string.no_data);
                    showHideNoDataLayout(true);
					
					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
				}
				showFirstLoadDataLayout(false);
				break;
			case MSG_DATA_FAIL:
				// 更新完后调用该方法结束刷新
				showFirstLoadDataLayout(false);
				showHideNoDataLayout(true);
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			mRefreshTime = BeanBbs.parseJsonDate((String) data);
			ArrayList<BeanMyArticle> dataArraylist = BeanMyArticle.parseListInfo((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		}
	}

	@Override
	public void notify(String arg0, Object arg1, Object arg2) {
		String type = (String)arg2;
		try {
			if(type.equals("favour")){
				mDataArrayList.get(mPosition).FavourCount = String.valueOf((Integer.valueOf(mDataArrayList.get(mPosition).FavourCount))+1);
				mDataAdapter.notifyDataSetChanged();
			}
			if(type.equals("view")){
				mDataArrayList.get(mPosition).ViewCount = String.valueOf((Integer.valueOf(mDataArrayList.get(mPosition).ViewCount))+1);
				mDataAdapter.notifyDataSetChanged();
			}
		}catch (Exception e){

		}
	}

}
